﻿using DotNetCore.CAP;
using Hangfire;
using Microsoft.AspNetCore.Mvc;
using Quartz;
using xk.mqm.test.common;
using xk.mqm.test.common.Entity;
using xk.mqm.test.userservice.MyJob;
using static Quartz.Logging.OperationName;

namespace xk.mqm.test.userservice.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class MqTestController : ControllerBase
    {
        private MyDBContext _dbcontext;

        private ICapPublisher _publisher;
        private readonly ISchedulerFactory _schedulerFactory;
        private IScheduler _scheduler;
        public MqTestController(MyDBContext myDBContext, ICapPublisher publisher, ISchedulerFactory schedulerFactory) {
            _dbcontext=myDBContext;
            _publisher = publisher;
            _schedulerFactory=schedulerFactory;
        }
        [HttpGet]
        public string Get(int id=1) {
            /*BackgroundJob.Enqueue("mytest", () => Console.WriteLine("0999999" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));*/
            BackgroundJob.Schedule( () => Console.WriteLine("0999999" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), TimeSpan.FromMilliseconds(20));
            using (var trans = _dbcontext.Database.BeginTransaction(_publisher, false))
            {

                IDictionary<string, string?> headers = new Dictionary<string, string?>();
                headers.Add("向奎", "很有钱");
                Users user = new Users()
                {
                    Account = "2323" + id,
                    UserName = "23232"
                };
                try
                {
                    _dbcontext.Users.Add(user);
                    _dbcontext.SaveChanges();
                    _publisher.Publish("xk.text.order-service", user, headers);
                    trans.Commit();
                    return "cg";
                }catch (Exception ex)
                {
                    trans.Rollback();
                    return "sb";
                }
               
            }
        }
        public async Task<bool> Index()
        {
            //通过工场类获得调度器
            _scheduler = await _schedulerFactory.GetScheduler();
            //开启调度器
            await _scheduler.Start();
            //创建触发器(也叫时间策略)
            var trigger = TriggerBuilder.Create()
                            .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).RepeatForever())//每10秒执行一次
                            .Build();
            //创建作业实例
            //Jobs即我们需要执行的作业
            var jobDetail = JobBuilder.Create<MyTestJob>()
                            .WithIdentity("Myjob", "group")//我们给这个作业取了个“Myjob”的名字，并取了个组名为“group”
                            .Build();
            //将触发器和作业任务绑定到调度器中
            await _scheduler.ScheduleJob(jobDetail, trigger);
            return true;
        }
    }
}
